from openpyxl import Workbook
from openpyxl.styles import Font, Alignment, Border, Side


def write_data_to_xlsx(data, file_path):
    """
    将数据写入XLSX表格

    参数:
    data: 要写入的二维数组数据
    file_path: 输出的文件路径，如 'output.xlsx'
    """
    # 创建工作簿
    wb = Workbook()
    # 获取活动工作表
    ws = wb.active
    # 设置工作表名称
    ws.title = "数据列表"

    # 定义表头
    headers = ['流水号', '申请主体', '事项名', '部门', '接收时间', '承诺时间']

    # 设置表头样式
    header_font = Font(bold=True, color="000000", size=11)
    alignment = Alignment(horizontal="center", vertical="center")
    # 设置边框
    side = Side(style='thin', color='000000')
    border = Border(left=side, right=side, top=side, bottom=side)

    # 写入表头
    for col, header in enumerate(headers, 1):
        cell = ws.cell(row=1, column=col)
        cell.value = header
        cell.font = header_font
        cell.alignment = alignment
        cell.border = border
        # 自动调整列宽
        ws.column_dimensions[chr(64 + col)].width = 20  # 64是ASCII码中'A'的前一个字符

    # 写入数据
    for row_idx, row_data in enumerate(data, 2):  # 从第2行开始写入数据
        for col_idx, value in enumerate(row_data[:6], 1):  # 只取前6列数据
            cell = ws.cell(row=row_idx, column=col_idx)
            cell.value = value if value is not None else ""  # 处理None值
            cell.alignment = alignment
            cell.border = border

    try:
        # 保存工作簿
        wb.save(file_path)
        print(f"数据已成功写入XLSX表格: {file_path}")
        return True
    except Exception as e:
        print(f"写入XLSX表格时发生错误: {str(e)}")
        return False


# 示例数据

# 使用示例

